

Vue.createApp({
    // 定义组件
    components:{
        'left-nav': LEFT_NAV,
        "message-user-info": MESSAGE_USER_INFO,
    },
    // 初始化
    setup(){
        // reactive定义变量运行存储
        // toRefs将数据返回
        const {
            reactive, toRefs
        } = Vue
        // 定义变量，即所需数据
        const state = reactive({
            menu:[
                {
                    name: '消息',
                    icon: 'envelope icon',
                    count: 0
                },
                {
                    name: '关注',
                    icon: 'user plus icon',
                    count: 0
                },
                {
                    name: '评论',
                    icon: 'comment icon',
                    count: 0
                },
                {
                    name: '喜欢',
                    icon: 'heart icon',
                    count: 0
                },

            ],
            showIndex: 0,
            showData: {},
            followView: {},
            fanView: {},
            comments: {},
            likes: {},
            urls:[
                '/getCommunicateFollowView',
                '/getCommunicateFanView',
                '/getCommentView',
                '/getLikeView'
            ],
            // 聊天状态，初始false
            isChat: false,
            responseUser: {},
            communicates: [],
            loginUser: {},
            followCount: 0,
            fanCount: 0,
            isOpen: false,
            beReplyComment: {}
        })
        // 初始化为关注列表
        get(state.urls[0], function (data) {
            data.forEach(e =>{
                // 添加一个字段用于保存当前交流数据长度
                e.communicates.count = e.communicates.length
                state.followCount += e.communicates.length
            })
            state.menu[0].count = state.followCount
            state.followView = data
        })
        get(state.urls[1], function (data) {
            data.forEach(e =>{
                e.communicates.count = e.communicates.length
                state.fanCount += e.communicates.length
            })
            state.menu[1].count = state.fanCount
            state.fanView = data
        })
        get(state.urls[2], function (data){
            state.comments = data
            state.menu[2].count = data.length
        })
        
        get(state.urls[3], function (data){
            state.likes = data
            state.menu[3].count = data.length
        })
        get("/loginUser", function (data) {
            state.loginUser = data
        })
        // enter键发送消息
        let websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket('ws://localhost:8080/webSocket');
        }
        else {
            alert('当前浏览器不支持websocket')
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log("WebSocket连接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            if (state.communicates) {
                state.communicates.push(JSON.parse(event.data))
                // 修改头部导航栏的消息数量
                // let message = $("#head #messageCount")
                // message.html(parseInt(message.html()) + 1)
                // message.show()
            }
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log("WebSocket连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send(content) {
            // 先保存数据
            post("/saveCommunicate/" + state.responseUser.userId, {
                content: content
            })
            websocket.send(JSON.stringify({
                content: content,
                requestUserId: state.loginUser.userId,
                responseUserId: state.responseUser.userId,
                createTime: getTime()
            }));
        }
        $(function () {
            let input = $("#myMessage #input")
            input.keydown(function (e) {
                if (e.which == 13) {
                    let message = input.val().trim()
                    if (message == "") {
                        swalError("发送失败", "发送的内容不能为空")
                        return
                    }
                    send(message)
                    input.val("")
                }
            })
        })

        // 返回数据
        return {
            ...toRefs(state)
        }
    },
    methods:{
        setShowIndex(showIndex) {
            this.isChat = false
            this.showIndex = showIndex
            let that = this
            that.menu[showIndex].count = 0
            get(this.urls[showIndex], function (data) {
                if (showIndex == 0) {
                    that.followView = data
                } else if (showIndex == 1) {
                    that.fanView = data
                } else if (showIndex == 2) {
                    that.comments = data
                } else {
                    that.likes = data
                }
            })
        },
        // 聊天
        chat(data) {
            autoFocus("#myMessage #inpu")
            this.isChat = true
            let that = this
            data.communicates.count = 0
            that.responseUser = data.follow
            that.communicates = data.communicates
        },
        // 回复
        reply() {
            let that = this
            let content = $("#myMessage #reply textarea").val().trim()
            if ("" == content) {
                swalError("回复失败", "回复内容不能为空")
                return
            }
            post("/replyByCommentId", {
                beReplyCommentId: that.beReplyComment.commentId,
                content: content
            }, function (success) {
                console.log(success);
                if (success) {
                    swalSuccess("回复成功", "回复内容审核后可见")
                    $("#myMessage #reply textarea").val("")
                    that.isOpen = false
                } else {
                    swalError("回复失败", "服务器竟然崩溃了")
                }
            }, function () {
                swalError("回复失败", "服务器竟然崩溃了")
            })
        },
        openWindow(item){
            autoFocus("#myMessage #reply textarea")
            this.isOpen = true
            this.beReplyComment = item
        }
    }
    // 绑定app
}).mount("#myMessage")

exchangeDisplay("#myMessage .leftNav .item", "#myMessage .messageList >div")
function getTime() {
    var date = new Date();
    var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
    var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
    var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

    var hours = date.getHours();          //小时 ,返回 Date 对象的小时 (0 ~ 23)
    var minutes = date.getMinutes();      //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
    var seconds = date.getSeconds();      //秒 ,返回 Date 对象的秒数 (0 ~ 59)   

    //修改月份格式
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }

    //修改日期格式
    if (day >= 0 && day <= 9) {
        day = "0" + day;
    }

    //修改小时格式
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
    }

    //修改分钟格式
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
    }

    //修改秒格式
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
    }

    //获取当前系统时间  格式(yyyy-mm-dd hh:mm:ss)
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

